package com.plan.dao.service.card.impl;

import com.plan.base.constant.BaseCode;
import com.plan.base.exception.BizException;
import com.plan.controller.card.request.BaseReq;
import com.plan.controller.card.response.CardListVO;
import com.plan.dao.mapper.card.CardMapper;
import com.plan.dao.mapper.card.DayPlanMapper;
import com.plan.dao.mapper.card.DayPlanStatMapper;
import com.plan.dao.mapper.card.TeamMapper;
import com.plan.dao.service.card.CardDaoService;
import com.plan.entity.card.Card;
import com.plan.entity.card.Team;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CardDaoServiceImpl implements CardDaoService {
    @Resource
    private CardMapper cardMapper;
    @Resource
    private TeamMapper teamMapper;
    @Resource
    private DayPlanMapper dayPlanMapper;
    @Resource
    private DayPlanStatMapper dayPlanStatMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(Card card, Team team) {
        teamMapper.update(team);
        return cardMapper.insert(card);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Card card) {
        return cardMapper.update(card);
    }

    @Override
    public Card selectOneById(Long teamId, Long cardId) {
        return cardMapper.selectOneById(teamId, cardId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BaseReq req, Team updateTeam, Card card) {
        cardMapper.update(card);
        int num = teamMapper.update(updateTeam);
        if (num != 1) {
            throw new BizException(BaseCode.DATA_BE_MODIFIED);
        }
        // 删除积分卡下面的计划
        dayPlanMapper.deleteAll(req.getTeamId(), req.getCardId());
        dayPlanStatMapper.delete(req.getTeamId(), req.getCardId());
    }

    @Override
    public List<CardListVO> list(Long teamId) {
        List<Card> list = cardMapper.list(teamId);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(x -> {
            CardListVO vo = new CardListVO();
            BeanUtils.copyProperties(x, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Card> selectWaitDeleteCard(Date start, Date end, Long preMaxId) {
        return cardMapper.selectWaitDeleteCard(start, end, preMaxId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void realDeleteByCardId(Long teamId, Long cardId) {
        int num = cardMapper.realDeleteByCardId(teamId, cardId);
    }
}
